﻿
$(function () {
    // 自定义验证
    var vm = new Vue({
        el: '#app',
        components: {
            // 局部注册组件
            'interval-box': IntevarBoxComponent
        },
        computed: {
            // 是否显示取消按钮
            showCancel() {
                const vm = this;
                var list = vm.selectedAppointedRows.filter(item => item.appointmentStatus === 2);// 是否有已到诊的预约
                var res;
                if (vm.selectedAppointedRows && vm.selectedAppointedRows.length > 0 && list.length === 0) {
                    res = true;
                } else {
                    res = false;
                }
                return res;
            },
            showConfirm: function () {
                const vm = this;
                var unConfirmList = vm.appointeds.filter(item => item.appointmentStatus === 0);
                if (unConfirmList.length === 0) {
                    return false;
                }
                return true;
            }
        },
        watch: {
            date: function (value) {
                var vm = this;
                if (vm.activeTabName === 'noAppoints') {
                    vm.noAppointDate = value;
                } else {
                    vm.appointedDate = value;
                }
            },
            deviceId: function (value) {
                const vm = this;
                if (value) {
                    vm.getDateLimit();
                }
                else {
                    axios.get(`/api/custom-setting/get-setting-detail?level=0`)
                        .then(res => {
                            if (res.code == 0) {
                                vm.limitDay = res.data.appointableCount;
                            }
                        });
                }
            }
        },
        data() {
            return {
                appointSetting: {},
                applyNumbers: null,
                hospitalName: null,
                logoUrl: '/iamges/logo/YALogo.png',
                selectableIds: [],  // 可被选中的申请项目
                tableHeight: 650,
                activeTabName: 'appointeds',
                autoAppointed:false,

                patientLoaded: false,
                patient: {
                    //name: '蒋小鱼',
                    //patientId: '10001',
                    //patientType: '门诊',                             // 患者类型
                    //ageValue: 25,
                    //ageUnit: 0,
                    //age: '',
                    //sex: 1,
                    //birthDate: '1990-4-19',
                    //parentName: '蒋中正',
                    //idCardNumber: '320323199004192019',             // 证件号
                    //medicalInsuranceType: '职工医保',               // 医保类型
                    //medicalInsuranceNumber: '32423423432432432',
                    //phoneNumber: '18914894368',
                    //ethnicGroup: '汉族',
                    //isPregnancy: true,     // 是否怀孕
                    //gestationalWeek: '25',   // 孕周
                    //lastMenstruationDate: '',
                    //LastMenstruationDateStr: '2025-9-18',
                    //isEmergency: true,     // 是否急诊患者
                },

                /*--表格部分 start--*/
                noAppoints: [],
                noAppointsLoading: false,
                noAppointDate: new Date(),
                noAppointDeviceType: null,
                noAppointSelectedIntervalId: null,
                noAppointSelectedIntervalName: null,
                noAppointSelectableIds: [], // 可选中Id集合
                selectedNoAppointRows: [],   // 被选中的行集合
                noAppointLoading: false,      // 是否展示加载动画
                reserveSelectionNoAppoint: true, // 是否回填选中

                appointeds: [],
                appointedsLoading: false,
                appointedDate: new Date(),
                appointedDeviceType: null,
                appointedSelectedIntervalId: null,
                appointedSelectedIntervalName: null,
                appointedSelectableIds: [],   // 可选中申请项目Id集合
                selectedAppointedRows: [],    // 被选中的行集合   
                appointedLoading: false,       // 是否展示加载动画
                reserveSelectionAppointed: true, // 是否回填选中
                /*--表格部分 end--*/


                /*--右侧时段选择  start--*/
                dateTimePickerDisable: true,
                // 范围快捷选项
                timeRangeOptions: [
                    { label: '今天', value: 'today', effect: 'dark' },
                    { label: '2天内', value: 'in2days', effect: 'plain' },
                    { label: '3天内', value: 'in3days', effect: 'plain' },
                    { label: '一周内', value: 'in1week', effect: 'plain' },
                    { label: '自定义', value: 'custom', effect: 'plain' },
                ],
                // 日期选择配置
                pickerOptions: {
                    disabledDate(time) {
                        const date = new Date();
                        return time.getTime() < (Date.now() - (24 * 60 * 60 * 1000)) || time.getTime() > date.setTime(date.getTime() + 3600 * 1000 * 24 * (vm.appointSetting.autoAppointableCount - 1));
                    },
                    shortcuts: [{
                        text: '今天',
                        onClick(picker) {
                            picker.$emit('pick', new Date());
                        }
                    }, {
                        text: '明天',
                        onClick(picker) {
                            const date = new Date();
                            date.setTime(date.getTime() + 3600 * 1000 * 24);
                            picker.$emit('pick', date);
                        }
                    }, {
                        text: '后天',
                        onClick(picker) {
                            const date = new Date();
                            date.setTime(date.getTime() + 3600 * 1000 * 24 * 2);
                            picker.$emit('pick', date);
                        }
                    }]
                },
                // 被选中的快捷范围
                selectedRangeIndex: 0,
                selectedRange: null,
                // 验证规则
                rules: {}
            }
        },
        methods: {
            // 同步申请项目
            syncApplyItems() {
                const vm = this;
                return new Promise((resolve, reject) => {
                    axios.get(`/api/his-appoint/sync-apply-items?applyItems=${vm.applyNumbers}`)
                        .then(res => {
                            if (res.data.code === 0) {
                                resolve();
                            } else {
                                vm.$message({
                                    message: res.msg,
                                    type: 'error'
                                })
                                reject();
                            }
                        });
                })
            },

            // 加载表格数据（同步后再行加载）
            loadData() {
                const vm = this;
                vm.appointedsLoading = true;
                vm.noAppointsLoading = true;
                // 异步加载两个表格数据
                vm.loadAppointeds()
                    .then(() => {
                        vm.selectedAppointedRows = [];
                        vm.appointedsLoading = false;
                        vm.$refs['appointed-table'].clearSelection();
                    });
                vm.loadNoAppoints()
                    .then(() => {
                        vm.selectedNoAppointRows = [];
                        vm.noAppointsLoading = false;
                        vm.$refs['noAppoint-table'].clearSelection();
                        vm.loading = false;
                    })
            },

            //　无需同步的加载
            loadWithOutSync() {
                const vm = this;
                vm.appointedsLoading = true;
                vm.noAppointsLoading = true;
                vm.loadAppointeds().then(() => {
                    vm.selectedAppointedRows = [];
                    vm.appointedsLoading = false;
                    vm.$refs['appointed-table'].clearSelection();
                })
                vm.loadNoAppoints().then(() => {
                    vm.selectedNoAppointRows = [];
                    vm.noAppointsLoading = false;
                    vm.$refs['noAppoint-table'].clearSelection();
                })
            },

            // 获取推荐号段
            getSuggestIntervals() {
                const vm = this;
                if (vm.activeTabName === 'noAppoints') { // 未预约
                    vm.noAppointSelectedIntervalId = null;
                    vm.noAppointSelectedIntervalName = null;
                    for (var i = 0; i < vm.noAppoints.length; i++) {
                        vm.noAppoints[i].intervalId = null;
                        vm.noAppoints[i].appointment = null;
                    }
                    vm.noAppoints == [...vm.noAppoints];
                    for (var i = 0; i < vm.selectedNoAppointRows; i++) {
                        vm.selectedNoAppointRows[i].intervalId = null;
                    }
                    vm.$refs.noAppointIntervalBox.getSuggestion();
                } else { // 已预约
                    vm.appointedSelectedIntervalId = null;
                    vm.appointedSelectedIntervalName = null;
                    for (var i = 0; i < vm.selectedAppointedRows; i++) {
                        vm.selectedAppointedRows[i] = null;
                    }
                    var selectedIds = vm.selectedAppointedRows.map(item => item.id);  
                    for (var i = 0; i < vm.appointeds.length; i++) {
                        if (selectedIds.includes(vm.appointeds[i].id)) {
                            vm.appointeds[i].intervalId = null;
                            vm.appointeds[i].appointment = vm.appointeds[i].oldInfo;
                            vm.appointeds[i].edited = false;
                        }
                    }
                    vm.appointeds = [...vm.appointeds];
                    vm.$refs.appointedIntervalBox.getSuggestion();
                }
            },

            /*--已预约相关 start--*/

            // (已预约)加载申请项目
            loadAppointeds() {
                const vm = this;
                return new Promise(resolve => {
                    if (vm.applyNumbers) {
                        axios.get(`/api/his-appoint/get-appointed-apply-items?applyNumbers=${vm.applyNumbers}`)
                            .then(res => {
                                let data = res.data;
                                if (data.code === 0) {
                                    vm.appointeds = data.data;
                                    vm.selectedAppointedRows = [];
                                    vm.appointedSelectableIds = data.data.map(item => item.id);
                                }
                            })
                    } else {
                        vm.$message({
                            message: 'url中applyNumbers为空！',
                            type: 'error'
                        })
                    }
                    resolve();
                })

            },

            //  (已预约)获取号段
            getAppointedsIntervals() {
                const vm = this;
                // 调用"时间段容器组件"的加载时间段方法
            },

            // (已预约)是否可选中
            getAppointedSelectable(row, index) {
                const vm = this;
                return vm.appointedSelectableIds.includes(row.id);
            },

            // (已预约)选中改变处理
            selectedAppointedChangeHandler(rows) {
                const vm = this;
                if (rows && rows.length > 0) {
                    vm.appointedDeviceType = rows[0].deviceTypeId;
                    vm.appointedSelectableIds = vm.appointeds.filter(item => item.deviceTypeId === vm.appointedDeviceType).map(item => item.id);
                    if (vm.appointedSelectedIntervalId && vm.appointedSelectedIntervalName) {
                        //var idList = rows.map(row => row.id);
                        //var oldRowIds = vm.selectedAppointedRows.map(row => row.id);
                        for (var i = 0; i < vm.appointeds.length; i++) {
                            vm.appointeds[i].appointment = vm.appointeds[i].oldInfo;
                            vm.appointeds[i].intervalId = vm.appointeds[i].oldIntervalId;
                            vm.appointeds[i].edited = false;
                        }
                    }
                } else {
                    vm.appointedDeviceType = null;
                    vm.appointedSelectableIds = vm.appointeds.map(item => item.id);
                    vm.appointedSelectedIntervalId = null;
                    vm.appointedSelectedIntervalName = null;
                    for (var i = 0; i < vm.appointeds.length; i++) {
                        vm.appointeds[i].appointment = vm.appointeds[i].oldInfo;
                        vm.appointeds[i].intervalId = vm.appointeds[i].oldIntervalId;
                        vm.appointeds[i].edited = false;
                    }
                }
                vm.selectedAppointedRows = rows;
                vm.appointeds = [...vm.appointeds];
            },

            // (已预约)选中号段改变事件
            appointedInteverChangeHandler(param) {
                const vm = this;
                if (param) {
                    vm.appointedSelectedIntervalId = param.id ? param.id : null;
                    vm.appointedSelectedIntervalName = param.name;
                    vm.selectedAppointedRows.forEach(row => {
                        row.edited = true;
                        row.appointment = vm.appointedSelectedIntervalName;
                        row.intervalId = vm.appointedSelectedIntervalId;
                        row.suggestionId = param.suggestionId;
                        for (var i = 0; i < vm.appointeds.length; i++) {
                            if (vm.appointeds[i].examItemNumber === row.examItemNumber) {
                                vm.appointeds[i] = row;
                            }
                        }
                    })
                    vm.appointeds = [...vm.appointeds]
                } else {
                    vm.appointedSelectedIntervalId = null;
                    vm.appointedSelectedIntervalName = null;
                }
            },

            // (已预约) 行点击事件
            appointedRowClick(row, event, column) {
                const vm = this;
                if (colum.type = 'selection' || !vm.appointedSelectableIds.includes(row.id)) {
                    return;
                }
                vm.$refs['appointed-table'].toggleRowSelection(row);
            },
            /*--已预约相关 end--*/



            /*--未预约相关 start--*/

            // (未预约)加载申请项目
            loadNoAppoints() {
                const vm = this;
                return new Promise(resolve => {
                    if (vm.applyNumbers) {
                        axios.get(`/api/his-appoint/get-noappoint-apply-items?applyNumbers=${vm.applyNumbers}`)
                            .then(res => {
                                let data = res.data;
                                if (data && data.code === 0) {
                                    vm.noAppoints = data.data;
                                    vm.selectedNoAppointRows = [];
                                    vm.noAppointSelectableIds = data.data.map(item => item.id);
                                }
                            })
                    } else {
                        vm.$message({
                            message: 'url中applyNumbers参数为空!',
                            type: 'error'
                        })
                    }
                    resolve();
                })
            },

            // (未预约)获取号段
            getNoAppointsIntervals() {
                const vm = this;
                // 调用"时间段容器组件"的加载时间段方法
            },

            // (未预约)是否可选中
            getNoAppointSelectable(row, index) {
                const vm = this;
                return vm.noAppointSelectableIds.includes(row.id);
            },

            // (未预约)选中改变事件处理
            selectedNoAppointChangeHandler(rows) {
                const vm = this;
                if (rows && rows.length > 0) {
                    vm.noAppointDeviceType = rows[0].deviceTypeId;
                    vm.noAppointSelectableIds = vm.noAppoints.filter(item => item.deviceTypeId === vm.noAppointDeviceType).map(item => item.id);
                    for (var i = 0; i < vm.noAppoints.length; i++) {
                        vm.noAppoints[i].appointment = null;
                        vm.noAppoints[i].intervalId = null;
                        vm.noAppoints[i].edited = false;
                    }

                } else {
                    vm.noAppointDeviceType = null;
                    vm.noAppointSelectableIds = vm.noAppoints.map(item => item.id);
                    vm.noAppointSelectedIntervalId = null;
                    vm.noAppointSelectedIntervalName = null;
                    for (var i = 0; i < vm.noAppoints.length; i++) {
                        vm.noAppoints[i].appointment = null;
                        vm.noAppoints[i].intervalId = null;
                        vm.noAppoints[i].edited = false;
                    }
                }
                vm.selectedNoAppointRows = rows;
                vm.noAppoints = [...vm.noAppoints];
            },

            // (未预约)选中号段改变
            noAppointIntervalChangeHandler(param) {
                const vm = this;
                if (param) {
                    vm.noAppointSelectedIntervalId = param.id ? param.id : null;
                    vm.noAppointSelectedIntervalName = param.name;
                    vm.selectedNoAppointRows.forEach(row => {
                        row.edited = true;
                        row.appointment = vm.noAppointSelectedIntervalName;
                        row.intervalId = param.id;
                        row.suggestionId = param.suggestionId;
                        for (var i = 0; i < vm.noAppoints.length; i++) {
                            if (vm.noAppoints[i].examItemNumber === row.examItemNumber) {
                                vm.noAppoints[i] = row;
                            }
                        }
                    });
                    vm.noAppoints = [...vm.noAppoints];
                } else {
                    vm.noAppointSelectedIntervalId = null;
                    vm.noAppointSelectedIntervalName = null;
                }
            },

            // (未预约)点击行事件
            noAppointedRowClick(row, event, column) {
                const vm = this;
                if (column.type = 'selection' || !vm.noAppointSelectableIds.includes(row.id)) { // 复选框列，不在选中之列
                    return;
                }
                vm.$refs['noAppoint-table'].toggleRowSelection(row);
            },

            /*--未预约相关 end--*/


            // 从url中解析 applyNumbers 参数
            getApplyNumbersFromQuery() {
                const vm = this;
                return new Promise((resolve, reject) => {
                    var numbers = window.utils.getQuery('applyNumbers');
                    var appointed = window.utils.getQuery('appointed');
                    if (!appointed) {
                        vm.$message({
                            message: '查询阐述appointed不能为空！',
                            type: 'error'
                        });
                        reject();
                    } else {
                        vm.autoAppointed = appointed === '0' ? false : true;
                    }
                    if (!numbers) {
                        vm.$message({
                            message: '未能从url query 中获取到正确的 applyNmbers 参数',
                            type: 'error'
                        });
                        reject();
                    }
                    else {
                        vm.applyNumbers = numbers;
                        resolve();
                    }
                });

            },

            // 加载页面初始化信息
            getInitInfo() {
                axios.get(`/api/his-appoint/get-init-info?applyNumbers=${vm.applyNumbers}`)
                    .then(res => {
                        if (res.data.code == 0) {
                            vm.patient = res.data.data.patient;
                            vm.patientLoaded = true;
                            vm.hospitalName = res.data.data.hospital;
                        }
                    });
            },

            // 确认方案
            confirm() {
                const vm = this;
                vm.$confirm('您正在确认当前预约方案，是否继续？', '方案确认', {
                    confirButtonText: '确定',
                    cancelButtonText: '取消'
                }).then(() => {
                    axios.get(`/api/his-appoint/confirm-solution?applyNumbers=${vm.applyNumbers}`)
                        .then(res => {
                            if (res.data.code === 0) {
                                vm.$message({
                                    message: res.data.msg,
                                    type: 'success'
                                })
                                for (var i = 0; i < vm.appointeds.length; i++) {
                                    vm.appointeds[i].appointmentStatus = 1;
                                    vm.appointeds = [...vm.appointeds];
                                }
                            } else {
                                vm.$message({
                                    message: res.data.msg,
                                    type: 'error'
                                });
                            }
                        })
                })
            },

            // 新建预约
            submit() {
                const vm = this;
                if (vm.selectedNoAppointRows && vm.selectedNoAppointRows.length > 0) {
                    var selectedIntervalId = vm.selectedNoAppointRows[0].intervalId;
                    if (!selectedIntervalId) {
                        vm.$message({
                            message: '未设置号段',
                            type: 'error'
                        });
                        return;
                    }
                    for (var i = 0; i < vm.selectedNoAppointRows.length; i++) {
                        if (!vm.selectedNoAppointRows[i].intervalId) {
                            vm.$message({
                                message: '未设置号段',
                                type: 'error'
                            })
                        } else if (!selectedIntervalId === vm.selectedNoAppointRows[i].intervalId) {
                            vm.$message({
                                message: '存在多个号段！',
                                type: 'error'
                            })
                        }
                    }
                    vm.$confirm('您正在提交预约，是否继续?', '预约提交', {
                        confirButtonText: '确定',
                        cancelButtonText: '取消'
                    }).then(() => {
                        axios.post('/api/his-appoint/submit-appoint', {
                            applyItems: vm.selectedNoAppointRows,
                            confirmed: !vm.showConfirm
                        }).then(res => {
                            if (res.data.code === 0) {
                                vm.$message({
                                    message: res.data.msg,
                                    type: 'success'
                                });
                                vm.loadWithOutSync();
                            } else {
                                vm.$message({
                                    message: res.data.msg,
                                    type: 'error'
                                })
                            }
                        })
                    })
                }
            },

            // 修改预约
            submitEdit() {
                const vm = this;
                if (vm.selectedAppointedRows.filter(item => !item.edited).length > 0) {
                    vm.$message({
                        message: '还未配置号段',
                        type: 'error'
                    });
                    return;
                }
                vm.$confirm('您正在修改申请项目的预约，是否继续？', '预约修改', {
                    confirButtonText: '确定',
                    cancelButtonText: '取消'
                }).then(() => {
                    if (!vm.selectedAppointedRows || vm.selectedAppointedRows.length === 0) {
                        vm.$message({
                            message: '未选中任何申请项目!',
                            type: 'warning'
                        })
                    } else {
                        axios.post('/api/his-appoint/edti-submit', {
                            applyItems: vm.selectedAppointedRows,
                            confirmed: !vm.showConfirm
                        }).then(res => {
                            if (res.data.code === 0) {
                                vm.$message({
                                    message: res.data.msg,
                                    type: 'success'
                                })
                                vm.loadWithOutSync();
                            } else {
                                vm.$message({
                                    message: res.data.msg,
                                    type: 'error'
                                })
                            }
                        })
                    }
                })
            },

            // 取消预约
            cancel() {
                const vm = this;
                vm.$confirm('您正在取消申请项目的预约，是否继续？', '预约取消', {
                    confirButtonText: '确定',
                    cancelButtonText: '取消'
                }).then(() => {
                    if (!vm.selectedAppointedRows || vm.selectedAppointedRows.length === 0) {
                        vm.$message({
                            message: '未选中任何申请项目！',
                            type: 'error'
                        })
                    } else {
                        axios.post(`/api/his-appoint/cancel`, {
                            applyItems: vm.selectedAppointedRows,
                            confirmed: !vm.showConfirm
                        })
                            .then(res => {
                                if (res.data.code === 0) {
                                    vm.$message({
                                        message: res.data.msg,
                                        type: 'success'
                                    })
                                    vm.loadWithOutSync();
                                } else {
                                    vm.$message({
                                        message: res.data.msg,
                                        type: 'error'
                                    });
                                }
                            })
                    }
                })
            },

            // js日期格式化
            format(date) {
                return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
            },

            // 初始化
            init() {
                const vm = this;
                vm.date = new Date();
                vm.getApplyNumbersFromQuery().then(() => {      // 解析url获取 applyNumbers
                    if (vm.autoAppointed) {
                        vm.getInitInfo();
                        vm.loadWithOutSync();
                    } else {
                        vm.syncApplyItems()
                            .then(() => {
                                vm.getInitInfo();
                                vm.loadData();
                            });
                    }
                });
            }
        },
        mounted() {
            const vm = this;
            vm.init();
        }
    });
});